//
//  UIImageView+Utils.swift
//  YueYTProject
//
//  Created by mingke on 2021/2/7.
//

import Foundation

extension UIImageView {
    
    func addStickerToSuperView(superView : UIView) {
        superView.addSubview(self);
        self.moveTolast();
    }
    
    func moveTolast() {
        //这个函数的目的在于，使得加入的图片能够位于页面的最后
        let maxY = findMaxY(parentView: self.superview!, skip: self);
        //获取到当前贴纸的中心点
        var point = self.center;
        //改变当前的贴纸的位置
        point.y = maxY + (self.frame.size.height / 2) + 8;
        self.center = point;
        //改变背景滚动视图的offset
        if let scroll = self.superview as? UIScrollView {
            let diff = self.frame.maxY - scroll.contentOffset.y - scroll.frame.height
            if diff > 0 {
                var offset = scroll.contentOffset
                offset.y += diff
                scroll.setContentOffset(offset, animated: true)
            }
        }
    }
    
    func findMaxY(parentView : UIView, skip : UIImageView) -> CGFloat {
        let children = parentView.subviews;
        var maxY : CGFloat = 0;
        for child in children {
            if let v = child as? Sticker, v !== skip {
                //跳过自身，寻找最大的Y
                if v.frame.maxY > maxY {
                    maxY = v.frame.maxY;
                }
            }
        }
        return maxY;
    }
}
